﻿using AutoScaleHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tool
{
    public partial class ReadCard : Form
    {
        AutoScale autoScale = new AutoScale();

        private bool _isLoaded = false;

        // 波特率数值范围
        private readonly List<string> baudList = new List<string>() {
           "600","1200", "2400", "4800", "9600","14400", "19200", "28800","38400", "43000", "57600",
           "76800","115200","128000","230400","256000","460800","921600","1382400","自定义"
        };

        // com口
        private readonly List<string> comList = new List<string>() {
           "COM1","COM2", "COM3", "COM4", "COM5","COM6", "COM7", "COM8","COM9", "COM10", "COM11",
           "COM12","COM13","COM14","COM15","COM16","COM17","COM18","COM19"
        };

        // 连接方式
        private readonly List<string> linkTypeList = new List<string>() {
           "USB","COM"
        };

        // 扇号
        private readonly List<string> fanList = new List<string>() {
           "0","1", "2", "3", "4","5", "6", "7","8", "9", "10","11","12","13","14","15"

        };

        //有效的设备句柄
        Int32 n_hDev = -1;



        public ReadCard()
        {
            InitializeComponent();
            autoScale.SetContainer(this);
        }


        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (_isLoaded)
            {
                this.SuspendLayout();
                autoScale.UpdateControlsLayout();
                this.ResumeLayout();
            }
        }

        private void ReadCard_Load(object sender, EventArgs e)
        {
            _isLoaded = true;
            InitBaud();
            InitCom();
            InitLinkType();
            InitFunType();
            InitBlockType();
            this.AuthButton.Enabled = false;
            this.ReadCardButton.Enabled = false;
            this.WriteButton.Enabled = false;  
        }



        /**
         * 初始化波特率
        */
        public void InitBaud()
        {
            this.BtComboBox.Items.Clear();
            foreach (var item in baudList)
            {
                this.BtComboBox.Items.Add(item);
            }
            this.BtComboBox.SelectedItem = "600";
        }


        /**
          * 初始化com口
          */
        public void InitCom()
        {
            this.ComNumBox.Items.Clear();
            foreach (var item in comList)
            {
                this.ComNumBox.Items.Add(item);
            }
            this.ComNumBox.SelectedItem = "COM1";
        }


        /**
         * 
         * 初始化LinkType
         */
        public void InitLinkType()
        {
            this.LinkTypeBox.Items.Clear();
            foreach (var item in linkTypeList)
            {
                this.LinkTypeBox.Items.Add(item);
            }
            this.LinkTypeBox.SelectedItem = "USB";
        }


        /**
         * 
         * 初始化Fun 扇号
         */
        public void InitFunType()
        {
            this.comboBox1.Items.Clear();
            foreach (var item in fanList)
            {
                this.comboBox1.Items.Add(item);
            }
            this.comboBox1.SelectedItem = "0";
        }



        /**
         * 
         * 初始化Block 块区
         */
        public void InitBlockType()
        {
            this.WriteBlockboBox.Items.Clear();
            this.ReadBlockboBox.Items.Clear();
            for (int i = 0; i < 60; i++)
            {
                this.WriteBlockboBox.Items.Add(i.ToString());
                this.ReadBlockboBox.Items.Add(i.ToString());
            }
            this.WriteBlockboBox.SelectedItem = "0";
            this.ReadBlockboBox.SelectedItem = "0";
        }






        private void OpenButton_Click(object sender, EventArgs e)
        {
            if (n_hDev == -1)
            {
                string linkType = this.LinkTypeBox.SelectedItem.ToString();
                if (linkType == "USB")
                {
                    //初始化连接读卡器
                    n_hDev = ComProDll.lc_init(100, 0);
                    if (n_hDev != -1)
                    {
                        MessageBox.Show("成功设备打开!");
                        this.OpenButton.Enabled = false;
                        this.CloseButton.Enabled = true;
                        return;
                    }
                    else
                    {
                        MessageBox.Show("设备打开失败!");
                        return;
                    }
                }
                else if (linkType == "COM")
                {
                    string com = this.ComNumBox.SelectedText;
                    string band = this.BtComboBox.SelectedText;
                    MessageBox.Show("暂未开通的方式!");
                    return;
                }
                else
                {
                    MessageBox.Show("错误的设备连接方式!");
                    return;
                }
            }
            else 
            {
                MessageBox.Show("设备打开失败!");
                return;
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 n_exit_ret_code =  ComProDll.lc_exit(n_hDev);
                if (n_exit_ret_code == 0)
                {
                    n_hDev = -1;
                    this.OpenButton.Enabled = true;
                    this.CloseButton.Enabled = false;
                    this.AuthButton.Enabled = false;
                    this.ReadCardButton.Enabled = false;
                    this.WriteButton.Enabled = false;
                    MessageBox.Show("设备关闭成功!");
                    return;
                }
                else 
                {
                    this.OpenButton.Enabled = false;
                    this.CloseButton.Enabled = true;
                    MessageBox.Show(n_exit_ret_code + "设备关闭失败!");
                    return;
                }
            }
            else 
            {
                MessageBox.Show("设备已经关闭!");
                return;
            }
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st = 0;
                Byte[] snCard = new Byte[20];
                Byte[] snSize = new Byte[2];
                Int32[] pTag = new Int32[2];
                Byte[] pSak = new Byte[2];
                st = ComProDll.lc_card(n_hDev, 0, snCard, snSize, pTag, pSak);
                if (st == 0)
                {
                    string cardNo = FormatBinDataToStr(snCard, (int)snSize[0]);
                    this.RetTextBox.Text = cardNo;
                    this.AuthButton.Enabled = true;
                    this.ReadCardButton.Enabled = true;
                    this.WriteButton.Enabled = true;
                }
                else
                {
                    MessageBox.Show(st + "寻卡失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
       
        }




        private string FormatBinDataToStr(Byte[] pBytes, int byteNum)
        {
            string strRel = "";
            Byte[] pByteItem = new Byte[2];
            Byte[] pszByte = new Byte[3];
            int i;
            for (i = 0; i < byteNum; i++)
            {
                pByteItem[0] = pBytes[i];
                ComProDll.hex_asc(pByteItem, pszByte, 1);
                pszByte[2] = (Byte)(' ');
                strRel += System.Text.Encoding.ASCII.GetString(pszByte);
            }
            return strRel;
        }

        private void ReadCardButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st = 0;
                Byte[] bufData = new Byte[20];
                Byte[] outBufData = new Byte[1024];
                Byte r_Adr = 4;
                st = ComProDll.lc_read(n_hDev, r_Adr, bufData);
                if (st == 0)
                {
                    ComProDll.hex_asc(bufData, outBufData, 20);
                    string result = Encoding.UTF8.GetString(outBufData);
                    this.RetTextBox.Text = result;
                }
                else
                {
                    MessageBox.Show(st + "读卡失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
        }

        private void AuthButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st;
                Byte[] bufData = new Byte[20];
                string str = this.PassWordTextBox.Text.Trim();
                //Byte[] defKey = Encoding.UTF8.GetBytes(str);
                Byte[] pszByte = new byte[6];
                string s = StringToHex(str);
                this.RetTextBox.Text = s;
                //ComProDll.asc_hex(defKey, pszByte, 6);
                Byte[] defKey = { 0xD3, 0xF7,  0xD3, 0xF7,  0xD3, 0xF7 };
                //return;
                //Byte[] defKey = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };// 卡密码 初始密码FFFFFFFFFFFF
                Byte sector = 1;//扇区地址 0~15
                Byte authenMode = 0x60;//密码模式，60h-密码 A, 61h-密码 B
                st = ComProDll.lc_authentication(n_hDev, authenMode, sector, defKey);
                if (st == 0)
                {
                    MessageBox.Show("卡密码验证成功!");
                }
                else
                {
                    MessageBox.Show(st + "卡密码验证失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
        }

        public static string StringToHex(string input)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(input);
            StringBuilder hex = new StringBuilder(byteArray.Length * 2);
            foreach (byte b in byteArray)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }

        private void WriteButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st = 0;
                Byte[] bufData = new Byte[1024];
                Byte[] outBufData = new Byte[1024];
                string inputStr = SendCmdTextBox.Text;
                /* Byte[] inBufData = new Byte[1024];
                 inBufData[0] = 1;*/
                //Byte[] inBufData = { 0x01, 0x02 };
                Byte[] inBufData = Encoding.UTF8.GetBytes("测试地址");
                Byte r_Adr = 4;
               // ComProDll.asc_hex(inBufData, outBufData, 1024);
                st = ComProDll.lc_writer(n_hDev, r_Adr, inBufData);
                if (st == 0)
                {
                    MessageBox.Show("写卡成功!");
                }
                else
                {
                    MessageBox.Show(st + "写卡失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
        }

        private void ReadTagButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st = 0;
                Byte[] bufData = new Byte[1024];
                Byte[] outBufData = new Byte[1024];
                string inputStr = SendCmdTextBox.Text;
                Int32[] recordTpye = new int[10];
                st = ComProDll.lc_NFC_ReadTag(n_hDev,0,3,"", recordTpye, bufData);
                string result = Encoding.UTF8.GetString(bufData);
                if (st == 0)
                {
                    MessageBox.Show("读卡标签成功!");
                    this.RetTextBox.Text = result;   
                }
                else
                {
                    MessageBox.Show(st + "读卡标签失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {

        }

        private void UpdatePasswordButton_Click(object sender, EventArgs e)
        {
            if (n_hDev != -1)
            {
                Int32 st = 0;
                Byte[] pNewKeyA = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
                Byte[] pNewCtrlW = { 0xff, 0xff, 0xff, 0xff };
                Byte[] pNewKeyB = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
                Byte secNr = 1;
                st = ComProDll.lc_updateKey(n_hDev, secNr, pNewKeyA, pNewCtrlW, pNewKeyB);
                if (st == 0)
                {
                    MessageBox.Show("修改密码成功!");
                }
                else
                {
                    MessageBox.Show(st + "修改密码失败!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先打卡设备!");
                return;
            }
        }
    }
}
